import { PlusOutlined } from '@ant-design/icons';
import type { ActionType, ProColumns, ProDescriptionsItemProps, ProFormInstance } from '@ant-design/pro-components';
import {
  FooterToolbar,
  PageContainer,
  ProDescriptions,
  ProFormText,
  ProFormTextArea,
  ProTable,
  ProFormSelect,
  ProForm,
  ModalForm,
} from '@ant-design/pro-components';
import { Button, Drawer, Form, message, Image, Popconfirm, Modal } from 'antd';
import React, { useRef, useState, useEffect } from 'react';
import { editSubtitle, pageAdd, pageQuery, updatepageQuery,pageRemove } from '@/services/ant-design-pro/home';
import { mjSolution } from '@/services/ant-design-pro/solution';
import { mjProduct } from '@/services/ant-design-pro/product';
import ImageUpload from '@/components/ImageUpload';
import { default as ReactQuill } from 'react-quill';
import 'react-quill/dist/quill.snow.css';
import { TableListItem } from '../table-list/data';
import { FormValueType } from '../table-list/components/UpdateForm';

const TableList: React.FC = () => {
  const [uploadUrl, setUploadUrl] = useState<string>('');
  const [drawerVisible, setDrawerVisible] = useState<boolean>(false);
  const [isEditing, setIsEditing] = useState<boolean>(false);
  const [showDetail, setShowDetail] = useState<boolean>(false);
  const [dropdownOptions, setDropdownOptions] = useState<{ label: string; value: string }[]>([]);
  const actionRef = useRef<ActionType>();
  const [currentRow, setCurrentRow] = useState<TableListItem>({});
  const [selectedRowsState, setSelectedRows] = useState<TableListItem[]>([]);
  const [subTitleOpen, setSubTitleOpen] = useState<boolean>(false);
  const [activeKey, setActiveKey] = useState<string>('1');
  const formRef = useRef<ProFormInstance>();
  const restFormRef = useRef<ProFormInstance>();
  const [tableData, setTableData] = useState([]);
  const fetchDropdownOptions = async (type: string) => {
    let options = [];
    if (type === '1') {
      const response = await mjSolution(); // Fetch solution options
      options = response.data.map((item: any) => ({ label: item.solutionName, value: item.id ,router: item.router }));
    } else if (type === '3') {
      const response = await mjProduct(); // Fetch product options
      options = response.data.map((item: any) => ({ label: item.productName, value: item.id ,router: item.router }));
    }
    setDropdownOptions(options);
  };

  useEffect(() => {
    fetchDropdownOptions(activeKey);
  }, [activeKey]);

  const handleAdd = async (fields: TableListItem) => {
    const hide = message.loading('正在添加');
    try {
      await pageAdd({ ...fields, url: uploadUrl, type: activeKey });
      hide();
      message.success('添加成功');
      return true;
    } catch (error) {
      hide();
      message.error('添加失败请重试！');
      return false;
    }
  };

  const newPageDeleteHandle = (id)=>{
    pageRemove({id}).then(()=>{
      message.success('删除成功');
      actionRef.current?.reload()
    })
  }

  const handleUpdate = async (fields: FormValueType, currentRow?: TableListItem) => {
    const hide = message.loading('正在配置');
    try {
      await updatepageQuery({
        ...currentRow,
        ...fields,
        url: uploadUrl,
      });
      hide();
      message.success('配置成功');
      return true;
    } catch (error) {
      hide();
      message.error('配置失败请重试！');
      return false;
    }
  };

  const subOk = () => {
    alert('ok')
  };
  const columns: ProColumns<TableListItem>[] = [
    {
      title: '图片',
      dataIndex: 'pictureUrl',
      render: (text) => <Image src={text} alt="图片" style={{ width: (activeKey === '1' || activeKey === '3') ? 90 : 40, height: 40 }} />,
      search: false,
      width: (activeKey === '1' || activeKey === '3') ? 110 : 60,
    },
    {
      title: '图片名称',
      width: 150,
      ellipsis: true,
      dataIndex: 'attributeTitle',
      render: (dom, entity) => (
        <a
          onClick={async () => {
            setCurrentRow(entity);
            setIsEditing(true);
            setDrawerVisible(true);
            setUploadUrl(entity.pictureUrl);
          }}
        >
          {dom}
        </a>
      ),
    },
    {
      title: '描述',
      dataIndex: 'attributeSubtitle',
      valueType: 'textarea',
      search: false,
      width: 200,
      ellipsis: true,
    },
    {
      title: '跳转链接',
      dataIndex: 'targetUrl',
      hideInForm: true,
      renderText: (val: string) => `${val || ''}`,
      search: false,
      ellipsis: true,
      hidden:true
    },
    {
      hidden: true,
      title: '状态',
      dataIndex: 'status',
      search: false,
      hideInForm: true,
      valueEnum: {
        0: {
          text: '启用',
          status: 'Default',
        },
        1: {
          text: '停用',
          status: 'Processing',
        },
      },
    },
    {
      title: '创建时间',
      sorter: true,
      dataIndex: 'createTime',
      valueType: 'date',
      width: 100,
      search: false,
      ellipsis: true,
      hidden: true
    },
    {
      title: '排序',
      dataIndex: 'sort',
      width: 50,
      ellipsis: true,
      search: false
    },
    {
      title: '操作',
      width: 150,
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => [
        <a
          key="config"
          onClick={() => {
            setCurrentRow(record);
            setIsEditing(true);
            setDrawerVisible(true);
            setUploadUrl(record.pictureUrl); // Set the initial upload URL
          }}
        >
          编辑
        </a>,
        <Popconfirm
          key="delete"
          title="确定删除吗？"
          onConfirm={() => newPageDeleteHandle(record.id)}
        >
          <a key="subscribeAlert"> 删除 </a>
        </Popconfirm>,
      ],
    },
  ];
  const openSubTitleModal = () => {
    const firstRowTypeTitle = tableData[0]?.typeSubtitle || '';
    setSubTitleOpen(true);
  };
  useEffect(() => {
    if (drawerVisible && formRef.current) {
      formRef.current.setFieldsValue(currentRow || {});
    }
  }, [drawerVisible, currentRow]);

  return (
    <PageContainer header={{ title: '' }}>
      <ProTable<TableListItem>
        headerTitle="查询表格"
        actionRef={actionRef}
        rowKey="id"
        search={false}
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              setIsEditing(false);
              setCurrentRow(undefined);
              setDrawerVisible(true);
              setUploadUrl(''); // Reset the upload URL
            }}
          >
            <PlusOutlined /> 新建
          </Button>,
        ]}
        toolbar={{
          menu: {
            type: 'tab',
            activeKey: activeKey,
            items: [
              { key: '1', label: <span>解决方案</span> },
              { key: '2', label: <span>关于我们</span> },
              { key: '3', label: <span>产品服务</span> },
            ],
            onChange: (key) => {
              setActiveKey(key as string);
              actionRef.current?.reloadAndRest();
            },
          },
          actions: [
            <Button
              key="create"
              type="primary"
              onClick={() => {
                setIsEditing(false);
                setCurrentRow(undefined);
                setDrawerVisible(true);
                setUploadUrl(''); // Reset the upload URL
              }}
            >
              新建首页信息
            </Button>,
            <Button onClick={()=>{
              restFormRef.current?.setFieldValue('typeSubtitle','123') ;
              setSubTitleOpen(true)
            }}>
              设置副标题
            </Button>
          ],
        }}
        request={(params) => {
          return pageQuery({ ...params, type: activeKey }).then(response => {
            setTableData(response.data);
            return response;
          });
        }}
        columns={columns}
        // rowSelection={{
        //   onChange: (_, selectedRows) => {
        //     setSelectedRows(selectedRows);
        //   },
        // }}
      />
      {selectedRowsState?.length > 0 && (
        <FooterToolbar
          extra={
            <div>
              已选择{' '}
              <a
                style={{
                  fontWeight: 600,
                }}
              >
                {selectedRowsState.length}
              </a>{' '}
              项 &nbsp;&nbsp;
            </div>
          }
        >
          <Button
            onClick={async () => {
              await handleRemove(selectedRowsState);
              setSelectedRows([]);
              actionRef.current?.reloadAndRest?.();
            }}
          >
            批量删除
          </Button>
        </FooterToolbar>
      )}
    <ModalForm
      title="副标题设置"   
      formRef={restFormRef}
      initialValues={{ typeSubtitle: tableData[0]?.typeSubtitle || '' }}
      modalProps={{
        destroyOnClose: true,
        onCancel: () => {
          setSubTitleOpen(false);
        },
      }}
      open={subTitleOpen}
      onFinish={async (values) => {
        await editSubtitle({type: activeKey, ...values});
        message.success('修改成功');
        setSubTitleOpen(false);
        actionRef.current?.reloadAndRest?.();
      }}
    >
      <ProFormText
        rules={[
          {
            required: true,
            message: '副标题内容必填',
          },
        ]}
        width="md"
        name="typeSubtitle"
      />
    </ModalForm>
      <Drawer
        title={isEditing ? '编辑' : '新建'}
        width={600}
        onClose={() => setDrawerVisible(false)}
        open={drawerVisible}
        destroyOnClose
      >
        <ProForm
          layout="vertical"
          formRef={formRef}
          initialValues={currentRow || {}}
          onFinish={async (value) => {
            const router =  dropdownOptions.find(item=>item.value ===  (currentRow&& currentRow.targetUrl))
            let success = false;
            if (isEditing) {
              success = await handleUpdate(value, {...currentRow, 'router': router.router});
            } else {
              success = await handleAdd({...value,router: router&& router.router});
            }

            if (success) {
              setDrawerVisible(false);
              if (actionRef.current) {
                actionRef.current.reload();
              }
            }
          }}
        >
          <ProFormText
            label="名称"
            rules={[{ required: true, message: '名称必填' }]}
            name="attributeTitle"
          />
           {activeKey==='1' &&<ProFormText name="attributeName" label="分类名称"    rules={[{ required: true, message: '请填写分类名称' }]} />}
       
         
          
          <ProFormTextArea name="attributeSubtitle" label="描述" rules={[{ required: true, message: '请填写描述' }]}  />
          <Form.Item
            name="content"
            label="内容"
            rules={[{ required: true, message: '请填写请填写内容类名称' }]} 
          >
            <ReactQuill
              className="my-editor"
              value={formRef.current?.getFieldValue('content')}
              modules={ {
                toolbar: [
                  [{ 'header': [1, 2, 3, 4, 5, 6, false] }],
                  ['bold', 'italic', 'underline', 'strike'], // 加粗、斜体、下划线、删除线
                  [{ 'color': [] }, { 'background': [] }], // 文字颜色、背景颜色
                  [{ 'align': [] }], // 对齐方式
                  ['blockquote', 'code-block'], // 引用、代码块
                  [{ 'list': 'ordered' }, { 'list': 'bullet' }], // 有序列表、无序列表
                  [{ 'script': 'sub' }, { 'script': 'super' }], // 下标、上标
                  [{ 'indent': '-1' }, { 'indent': '+1' }], // 减少缩进、增加缩进
                  [{ 'direction': 'rtl' }], // 文字方向
                  ['clean'], // 清除格式
                ],
              }}
              onChange={(value) => formRef?.current?.setFieldsValue({ content: value })}
            />
          </Form.Item>
          <ProFormSelect
            hidden={true}
            name="type"
            label="位置"
            options={[
              { label: '解决方案', value: '1' },
              { label: '关于我们', value: '2' },
              { label: '产品服务', value: '3' },
            ]}
            placeholder="请选择位置"
          />
          <ProFormSelect
            name="targetUrl"
            label="跳转路径"
            options={dropdownOptions}
            onChange={(value) => {
              setCurrentRow({ ...currentRow, targetUrl: value })
            }
}
            placeholder="请选择跳转链接"
            hidden={activeKey === '2' ? true : false}
          />
          <ProForm.Item
            name="pictureUrl"
            label="图片"
            rules={[{ required: true, message: '请上传图片' }]}
          >
            <ImageUpload maxHeight={422} maxWidth={634} value={uploadUrl} onChange={(url) => setUploadUrl(url)} />
          </ProForm.Item>
          <ProFormText label="图片alt" name="alt"></ProFormText>
          <ProFormText label="排序" name="sort"></ProFormText>
        </ProForm>
      </Drawer>
      <Drawer
        width={600}
        open={showDetail}
        onClose={() => {
          setCurrentRow(undefined);
          setShowDetail(false);
        }}
        closable={false}
      >
        {currentRow?.attributeTitle && (
          <ProDescriptions<TableListItem>
            column={2}
            title={currentRow?.attributeTitle}
            request={async () => ({
              data: currentRow || {},
            })}
            params={{
              id: currentRow?.attributeTitle,
            }}
            columns={columns as ProDescriptionsItemProps<TableListItem>[]}
          />
        )}
      </Drawer>
    </PageContainer>
  );
};

export default TableList;
